//
//  VOLHouseAllInfoViewController.m
//  Volver
//
//  Created by administrator on 14-9-16.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLHouseAllInfoViewController.h"
#import "common.h"
#import "HTTPDefine.h"
#import "ASIHTTPRequest.h"
#import "JSONKit.h"
#import "MBProgressHUD.h"

#import "VOLAppDelegate.h"
#import "Facility.h"
#import "VOLAppDelegate.h"
#import "FacilityIcon.h"
#import "User.h"
#import "House.h"
#import "Facility.h"
#import "VOLMyHouseViewController.h"
#import "VOLBookHouseViewController.h"
#import "VOLCommentViewController.h"
#import "VOLChatViewController.h"
#import "VOLDescribeViewController.h"
#import "PersonDataViewController.h"
#import "VOLLoginViewController.h"

#import "BWJHouseImageShowVIew.h"
#import "BWJLandLordView.h"
#import "BWJBaseInfo.h"
#import "BWJFacilityView.h"
#import "BWJDescripeView.h"
#import "BWJCommentView.h"
#import "BWJFacilityIcon.h"
#import "BWJHouseOwnerView.h"
#import "VOLGoThereViewController.h"

@interface VOLHouseAllInfoViewController ()
{
    int currentHeight;
    NSMutableArray *facilities;
    BOOL flag;
    VOLAppDelegate *del;
    
    JSONDecoder *jd;
    NSFileManager *manager;
    
    //即将被关闭的房屋的ID
    int willBeClosedHouseID;
    
    //缓冲动画提示
    MBProgressHUD *HUD;
    
    //创建user,house,facility对象，当来源不是发布都预览时，创建并初始化这三个对象
    User *houseOwner;
    House *willShowHouse;
    Facility *houseFacility;
    NSMutableArray *houseImageArray;
    
    NSString *userphone; //房东的电话号码
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@end

@implementation VOLHouseAllInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //添加返回按钮
    addBackButton();
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationBarBg.png"] forBarMetrics:UIBarMetricsDefault];
    
    del = kGetDel;
    jd = [[JSONDecoder alloc] init];
    manager = [NSFileManager defaultManager];
    
#pragma mark - 判断跳转的来源，根据来源，加载相应的内容
    //缓冲动作效果
    UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    CGRect temp = activity.frame;
    temp.size = CGSizeMake(80, 80);
    activity.frame = temp;
    activity.center = CGPointMake(kViewWidth/2, kViewHeight/2);
    activity.color = kThemeColor;
    activity.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.7];
    activity.hidesWhenStopped = YES;
    [self.view addSubview:activity];
    [activity startAnimating];
    
    
    switch (self.sourceFrom) {
            
        case 0:
            //来自发布房屋时的预览
            [self previewTheHouse:del.publishHouse houseFacility:del.publishFacility houseOwner:del.currentUser houseImageArray:del.selectedHouseImages];
            [activity stopAnimating];
            break;
        case 1:
            //来自我的房源
        {
            NSLog(@"来自我的房源");
            NSLog(@"houseID = %d",self.houseID);
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //初始化willShowHouse和houseFacility
                willShowHouse = [[House alloc] init];
                houseFacility = [[Facility alloc] init];
                houseImageArray = [NSMutableArray array];
                
                //根据传来的houseID获取整个房屋的信息
                [self getHouseByHouseID:self.houseID];
                
                //根据加载到的便利设施的ID加载便利设施的信息
                [self getFacilityByFacilityID:willShowHouse.houseFacility];
                
                //根据传来的houseID加载这个房子的所有图片名字
                [self getAllHouseImages:self.houseID];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //调用初始化方法，加载预览界面内容
                    [self previewTheHouse:willShowHouse houseFacility:houseFacility houseOwner:del.currentUser houseImageArray:houseImageArray];
                    [activity stopAnimating];
                });
            });
        }
            break;
        case 2:
        {
            NSLog(@"来自精选");
            NSLog(@"houseID = %d",self.houseID);
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //初始化houseOwner、willShowHouse、houseFacility、houseImageArray
                houseOwner = [[User alloc] init];
                willShowHouse = [[House alloc] init];
                houseFacility = [[Facility alloc] init];
                houseImageArray = [NSMutableArray array];
                
                //根据传来的userID获取房东的信息
                [self getHouseOwnerByUserID:self.userID];
                
                //根据传来的houseID获取整个房屋的信息
                [self getHouseByHouseID:self.houseID];
                
                //根据加载到的便利设施的ID加载便利设施的信息
                [self getFacilityByFacilityID:willShowHouse.houseFacility];
                
                //根据传来的houseID加载这个房子的所有图片名字
                [self getAllHouseImages:self.houseID];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //调用初始化方法，加载预览界面内容
                    [self previewTheHouse:willShowHouse houseFacility:houseFacility houseOwner:houseOwner houseImageArray:houseImageArray];
                    [activity stopAnimating];
                });
            });
        }
            break;
        case 3:
        {
            NSLog(@"来自收藏夹");
            NSLog(@"houseID = %d",self.houseID);
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //初始化houseOwner、willShowHouse、houseFacility、houseImageArray
                houseOwner = [[User alloc] init];
                willShowHouse = [[House alloc] init];
                houseFacility = [[Facility alloc] init];
                houseImageArray = [NSMutableArray array];
                
                //根据传来的userID获取房东的信息
                [self getHouseOwnerByUserID:self.userID];
                
                //根据传来的houseID获取整个房屋的信息
                [self getHouseByHouseID:self.houseID];
                
                //根据加载到的便利设施的ID加载便利设施的信息
                [self getFacilityByFacilityID:willShowHouse.houseFacility];
                
                //根据传来的houseID加载这个房子的所有图片名字
                [self getAllHouseImages:self.houseID];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //调用初始化方法，加载预览界面内容
                    [self previewTheHouse:willShowHouse houseFacility:houseFacility houseOwner:houseOwner houseImageArray:houseImageArray];
                    [activity stopAnimating];
                });
            });
        }
            break;
    }
    
    //    [activity stopAnimating];
    
}

#pragma mark - 展示预览界面内容
-(void)previewTheHouse:(House *)house houseFacility:(Facility *)showHouseFacility houseOwner:(User *)user houseImageArray:(NSMutableArray *)imageArray{
    
    userphone =  user.userPhone ;//获取房东的号码
    
    self.title = house.houseTitle;
    
    //用来控制各个控件高度位置的全局变量
    currentHeight = 0;
    
    //如果不是发布房间时的预览，要加载指定的信息，出现预订按钮
    if (self.sourceFrom == 2||self.sourceFrom == 3) {
        //首先判断是否登录，如果没有登录，直接置flag为NO
        if (del.isLogin) {
            //初始化flag，代表收藏状态，根据userID和houseID去查询，如果能查到，flag = YES，否则为NO
            flag = [self isFavoriteWithCurrentUserID:del.currentUser.userID houseID:house.houseID];
        }else{
            flag = NO;
        }
        
#pragma mark - 添加预订按钮
        UIButton *yudingBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, kViewHeight - 44, kViewWidth, 44)];
        yudingBtn.backgroundColor = [UIColor colorWithRed:1 green:90.0/255 blue:95.0/255 alpha:0.9];
        
        //添加预订动作
        [yudingBtn addTarget:self action:@selector(bookHouse:) forControlEvents:UIControlEventTouchUpInside];
        
        [yudingBtn setTitle:@"申请预订" forState:UIControlStateNormal];
        [yudingBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [yudingBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
        
        [self.view addSubview:yudingBtn];
    }
    
    //如果是从我的房源跳转过来时，出现关闭房源按钮
    if (self.sourceFrom == 1) {
#pragma mark - 添加关闭按钮
        UIButton *closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, kViewHeight - 44, kViewWidth, 44)];
        closeBtn.backgroundColor = [UIColor colorWithRed:1 green:90.0/255 blue:95.0/255 alpha:0.9];
        
        [closeBtn setTitle:@"关闭房源" forState:UIControlStateNormal];
        [closeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [closeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
        //记录当前即将被关闭的房屋的ID
        willBeClosedHouseID = house.houseID;
        //添加事件
        [closeBtn addTarget:self action:@selector(closeHouse:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:closeBtn];
    }
    
    
    
    
    
    //设置scrollView的内容界面大小
    self.scrollView.contentSize = CGSizeMake(kViewWidth, 2000);
    
#pragma mark - 滚动显示图片
    
    NSArray *imagenib = [[NSBundle mainBundle] loadNibNamed:@"BWJHouseImageShowView" owner:self options:nil];
    BWJHouseImageShowVIew *houseImageShow = imagenib[0];
    houseImageShow.center = CGPointMake(kViewWidth/2, currentHeight + houseImageShow.bounds.size.height / 2);
    houseImageShow.imageScrollView.contentSize = CGSizeMake(kViewWidth * imageArray.count, 200);
    houseImageShow.imageScrollView.pagingEnabled = YES;
    houseImageShow.imageScrollView.showsHorizontalScrollIndicator = NO;
#pragma mark 收藏按钮
    houseImageShow.favoriteButton.tag = 1000;
    //根据跳转来源情况判断是否出现收藏按钮
    if (self.sourceFrom == 2||self.sourceFrom == 3) {
        if (flag) {
            [houseImageShow.favoriteButton setBackgroundImage:[UIImage imageNamed:@"favoriteafter"] forState:UIControlStateNormal];
        }else{
            [houseImageShow.favoriteButton setBackgroundImage:[UIImage imageNamed:@"favoritebefore"] forState:UIControlStateNormal];
        }
        [houseImageShow.favoriteButton addTarget:self action:@selector(collectHouse:) forControlEvents:UIControlEventTouchUpInside];
    }else{
        houseImageShow.favoriteButton.hidden = YES;
    }
    
    
#pragma mark 添加图片
    
    //设置代理
    houseImageShow.imageScrollView.delegate = self;
    //根据来源添加要滚动显示的图片
    if (imageArray.count != 0) {
        if (self.sourceFrom == 0) {
            for (int i = 0; i < imageArray.count; i++) {
                UIImageView *houseImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kViewWidth * i, 0, kViewWidth, 200)];
                houseImageView.image = [UIImage imageWithData:imageArray[i]];
                [houseImageShow.imageScrollView addSubview:houseImageView];
            }
            
        }
        else{
            [self loadAllHouseImagesWithHouseID:house.houseID imageArray:imageArray imageScrollView:houseImageShow.imageScrollView];
        }
    }
    
    
    //将这图片显示模块加入到scrollView中
    [self.scrollView addSubview:houseImageShow];
    
    
    
#pragma mark 显示价格
    houseImageShow.priceLabel.backgroundColor = kPriceLabelColor;
    houseImageShow.priceLabel.textColor = [UIColor whiteColor];
    houseImageShow.priceLabel.text = [NSString stringWithFormat:@"￥%.1f",house.housePrice];
    houseImageShow.priceLabel.tag = 180;
    
    
#pragma mark 更新currentHeight
    currentHeight += houseImageShow.frame.size.height;
    
#pragma mark - 添加用户信息
    
    
    NSArray *landlordnib = [[NSBundle mainBundle] loadNibNamed:@"BWJLandLordView" owner:self options:nil];
    BWJLandLordView *landlordView = landlordnib[0];
    landlordView.center = CGPointMake(kViewWidth/2, currentHeight + landlordView.bounds.size.height/2);
    
    
#pragma mark 地址label
    
    landlordView.addressLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:14];
    
    //地址信息
    NSString *houseAddress = [NSString stringWithFormat:@"%@%@%@",house.houseProvince,house.houseCity,house.houseStreet];
    
    landlordView.addressLabel.text = houseAddress;
    
#pragma mark 头像
    
    
    landlordView.landlordHeadImageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    landlordView.landlordHeadImageView.contentMode = UIViewContentModeScaleAspectFill;
    
    if ((NSNull *)user.userHead != [NSNull null]) {
        NSLog(@"加载用户的头像");
        
        
        //加载图片
        //先判断是否有这个路径存在，如果没有要先创建
        NSString *imageDocumentPath = [NSString stringWithFormat:@"%@%d/userHead/%d",kGetDocumentsPath,del.currentUser.userID,user.userID];
        if (![manager fileExistsAtPath:imageDocumentPath]) {
            [manager createDirectoryAtPath:imageDocumentPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        //先从本地查找是否已有图片
        NSString *imagePath = [NSString stringWithFormat:@"%@%d/userHead/%d/%@",kGetDocumentsPath,del.currentUser.userID,user.userID,user.userHead];
        if ([manager fileExistsAtPath:imagePath]) {
            landlordView.landlordHeadImageView.image = [UIImage imageWithContentsOfFile:imagePath];
        }
        else{
            //若不存在，调用方法下载图片
            [del loadHeadImage:user.userHead userID:user.userID headImageView:landlordView.landlordHeadImageView imagePath:imagePath];
        }
        
        
        //        NSString *urlstr = [NSString stringWithFormat:@"%@%d/%@",kUserHeadHome,user.userID];
    }
    else{
        landlordView.landlordHeadImageView.image = [UIImage imageNamed:@"defaultHead.png"];
    }
    
    //设置圆形头像
    landlordView.landlordHeadImageView.layer.masksToBounds = YES;
    landlordView.landlordHeadImageView.layer.cornerRadius = 50.0;
    landlordView.landlordHeadImageView.layer.borderColor = [UIColor whiteColor].CGColor;
    landlordView.landlordHeadImageView.layer.borderWidth = 3.0;
    
    landlordView.landlordHeadImageView.layer.rasterizationScale = [UIScreen mainScreen].scale;
    landlordView.landlordHeadImageView.layer.shouldRasterize = YES;
    landlordView.landlordHeadImageView.clipsToBounds = YES;
    
#pragma mark 房屋类型label
    
    
    NSString *houseTypeStr = [self getHouseType:house.houseType];
    landlordView.houseTypeLabel.text = houseTypeStr;
    landlordView.houseTypeLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:12];
    
    
    
#pragma mark 房东名字
    
    
    NSString *name = user.userName;
    landlordView.nameLabel.text = [NSString stringWithFormat:@"房东:%@",name];
    landlordView.nameLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:12];
    landlordView.nameLabel.textColor = [UIColor colorWithRed:62/255.0f green:68/255.0f blue:75/255.0f alpha:1.0f];
    
#pragma mark - 联系房东
    [landlordView.contactButton addTarget:self action:@selector(contactHouseOwner:) forControlEvents:UIControlEventTouchUpInside];
#pragma mark 导航按钮
    [landlordView.mapButton addTarget:self action:@selector(goDestinationMap) forControlEvents:UIControlEventTouchUpInside];
    [landlordView.mapButton setBackgroundImage:[UIImage imageNamed:@"mapicon.png"] forState:UIControlStateNormal];
    
    [self.scrollView addSubview:landlordView];
    
    currentHeight += landlordView.frame.size.height;
    
#pragma mark - 房屋基本信息
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"BWJBaseInfoView" owner:self options:nil];
    BWJBaseInfo *baseInfo = nib[0];
    
    baseInfo.personNumLabel.text = [NSString stringWithFormat:@"%d位房客",house.housePersons];
    baseInfo.roomNumLabel.text = [NSString stringWithFormat:@"%d个房间",house.houseBedroom];
    baseInfo.bedNumLabel.text = [NSString stringWithFormat:@"%d张床",house.houseBed];
    baseInfo.toiletNumLabel.text = [NSString stringWithFormat:@"%d个卫生间",house.houseToilet];
    
    baseInfo.center = CGPointMake(kViewWidth/2, currentHeight + baseInfo.bounds.size.height/2);
    
    [self.scrollView addSubview:baseInfo];
    
    currentHeight += baseInfo.frame.size.height;
    
#pragma mark - 房屋描述
    NSArray *descnib = [[NSBundle mainBundle] loadNibNamed:@"BWJDescripeView" owner:self options:nil];
    BWJDescripeView *descripeView = descnib[0];
    descripeView.center = CGPointMake(kViewWidth/2, currentHeight + descripeView.bounds.size.height/2);
    [descripeView.descButton addTarget:self action:@selector(goToDesc:) forControlEvents:UIControlEventTouchUpInside];
    //    NSString *content = @"苏州，古称吴，简称苏，又称姑苏、平江等[1] ，中国华东地区特大城市之一，位于江苏省东南部、长江以南、太湖东岸、长江三角洲中部。\
    //    苏州以其独特的园林景观被誉为“中国园林之城”，素有“人间天堂”、“东方威尼斯”、“东方水城”的美誉。苏州园林是中国私家园林的代表，被联合国教科文组织列为世界文化遗产。\
    //    苏州历史悠久，是中国首批24座历史文化名城之一，是吴文化的发祥地和集大成者，历史上长期是江南地区的政治、经济、文化中心。苏州城始建于公元前514年，历史学家顾颉刚先生经过考证，认为苏州城为中国现存古老的城市之一。";
    
    NSString *content = house.houseDesc;
    descripeView.contentLabel.text = content;
    
    
    [self.scrollView addSubview:descripeView];
    
    currentHeight += descripeView.frame.size.height;
    
#pragma mark - 房屋评论
    //当来源不是用户预览时添加查看评论模
    if (self.sourceFrom == 2||self.sourceFrom == 3) {
        NSArray *commentnib = [[NSBundle mainBundle] loadNibNamed:@"BWJCommentView" owner:self options:nil];
        BWJCommentView *commentView = commentnib[0];
        commentView.center = CGPointMake(kViewWidth/2, currentHeight + commentView.bounds.size.height/2);
        [commentView.commentButton addTarget:self action:@selector(goToComment:) forControlEvents:UIControlEventTouchUpInside];
        
        
        //根据houseID去comment表中查询这个房屋的平均评分
        
        
        
        float score = house.houseScore;
        commentView.scoreLabel.textColor = kThemeColor;
        commentView.scoreLabel.text = [NSString stringWithFormat:@"%.1f分",score];
        
        
        [self.scrollView addSubview:commentView];
        
        currentHeight += commentView.frame.size.height;
    }
    
    
    
#pragma mark - 便利设施
    
    NSArray *facilitynib = [[NSBundle mainBundle] loadNibNamed:@"BWJFacilityView" owner:self options:nil];
    BWJFacilityView *facilityView = facilitynib[0];
    facilityView.center = CGPointMake(kViewWidth/2, currentHeight + facilityView.bounds.size.height/2);
    
    
    //数据源
    facilities = [NSMutableArray array];
    
    [self allHaveFacility:showHouseFacility];
    
    //展示已选的便利设施
    facilityView.facilityScrollView.contentSize = CGSizeMake(80 * facilities.count, 60);
    facilityView.facilityScrollView.showsHorizontalScrollIndicator = NO;
    for (int i = 0; i < facilities.count; i++) {
        NSArray *iconnib = [[NSBundle mainBundle] loadNibNamed:@"BWJFacilityIconView" owner:self options:nil];
        BWJFacilityIcon *iconView = iconnib[0];
        iconView.frame = CGRectMake(i * 80, 0, 60, 60);
        
        iconView.iconImageView.image = [UIImage imageNamed:[facilities[i] imageName]];
        iconView.iconLabel.text = [facilities[i] labelText];
        
        [facilityView.facilityScrollView addSubview:iconView];
    }
    
    
    
    [self.scrollView addSubview:facilityView];
    
    currentHeight += facilityView.bounds.size.height;
    
#pragma mark - 房东信息
    NSArray *ownernib = [[NSBundle mainBundle] loadNibNamed:@"BWJHouseOwnerView" owner:self options:nil];
    BWJHouseOwnerView *houseOwnerView = ownernib[0];
    houseOwnerView.center = CGPointMake(kViewWidth/2, currentHeight + houseOwnerView.bounds.size.height/2);
    
    //    NSDate *now = [NSDate date];
    
    
    
    //用户注册时间
    double userRegisterTime = user.userRegisterTime;
    //房屋发布时间
    double housePublishTime = house.houseDate;
    //    NSTimeInterval housePublishTime = [now timeIntervalSince1970];
    //房屋失效时间
    double houseExpirationTime = house.houseExpirationdate;
    
    //将秒数转换为日期类型
    
    NSDate *userRegisterDate = kTransformToDate(userRegisterTime);
    NSDate *housePublishDate = kTransformToDate(housePublishTime);
    NSDate *houseExpirationDate = kTransformToDate(houseExpirationTime);
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    
    houseOwnerView.registerTimeLabel.text = [formatter stringFromDate:userRegisterDate];
    
    houseOwnerView.publishTimeLabel.text = [formatter stringFromDate:housePublishDate];
    houseOwnerView.stopTimeLabel.text = [formatter stringFromDate:houseExpirationDate];
    
    [houseOwnerView.moreButton addTarget:self action:@selector(readMore:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.scrollView addSubview:houseOwnerView];
    
    currentHeight += houseOwnerView.bounds.size.height;
    
    self.scrollView.contentSize = CGSizeMake(kViewWidth, currentHeight + 30);
}
#pragma mark 进入界面时的刷新
-(void)viewWillAppear:(BOOL)animated{
    if (self.sourceFrom == 2||self.sourceFrom == 3) {
        //首先判断是否登录，如果没有登录，直接置flag为NO
        if (del.isLogin) {
            //初始化flag，代表收藏状态，根据userID和houseID去查询，如果能查到，flag = YES，否则为NO
            flag = [self isFavoriteWithCurrentUserID:del.currentUser.userID houseID:willShowHouse.houseID];
        }else{
            flag = NO;
        }
        //如果flag为真，设置收藏按钮的状态
        if (flag) {
            UIButton *favoriteBtn = (UIButton *)[self.view viewWithTag:1000];
            if (flag) {
                [favoriteBtn setBackgroundImage:[UIImage imageNamed:@"favoriteafter"] forState:UIControlStateNormal];
            }else{
                [favoriteBtn setBackgroundImage:[UIImage imageNamed:@"favoritebefore"] forState:UIControlStateNormal];
            }
            [favoriteBtn addTarget:self action:@selector(collectHouse:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
}

#pragma mark - 按钮点击事件方法

#pragma mark 查询该房屋是否被收藏，参数：当前用户ID和当前展示房屋ID
-(BOOL)isFavoriteWithCurrentUserID:(int)userID houseID:(int)houseID{
    
    NSString *urlstr = [NSString stringWithFormat:@"%@favorite/isfavorite?userID=%d&houseID=%d",kHTTPHome,userID,houseID];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    
    NSData *data = [request responseData];
    NSDictionary *dic = [jd objectWithData:data];
    int status = [[dic objectForKey:@"status"] intValue];
    if (status) {
        return YES;
    }
    
    return NO;
}

#pragma mark 预订按钮点击事件
-(void)bookHouse:(id)sender{
    if (del.isLogin) {
        VOLBookHouseViewController *bookHouseVC = [self.storyboard instantiateViewControllerWithIdentifier:@"bookHouseController"];
        bookHouseVC.house = willShowHouse;
        [self.navigationController pushViewController:bookHouseVC animated:YES];
    }else{
        VOLLoginViewController *loginvc = [self.storyboard instantiateViewControllerWithIdentifier:@"loginController"];
        [self presentViewController:loginvc animated:YES completion:^{
            
        }];
    }
    
}


#pragma mark 关闭房源按钮点击事件
-(void)closeHouse:(UIButton *)sender{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定关闭房源？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    
}



#pragma mark 收藏房屋
-(void)collectHouse:(UIButton *)sender{
    //未登录时不能收藏，直接跳到登录界面
    if (!del.isLogin) {
        VOLLoginViewController *loginvc = [self.storyboard instantiateViewControllerWithIdentifier:@"loginController"];
        [self presentViewController:loginvc animated:YES completion:^{
            
        }];
        return;
    }
    
    
    flag = !flag;
    
    if (flag) {
        NSLog(@"已收藏");
        //执行收藏操作
        if ([self addOrDeleteFavorite:del.currentUser.userID houseID:willShowHouse.houseID flag:flag]) {
            HUD = [[MBProgressHUD alloc] initWithView:self.view];
            [self.view addSubview:HUD];
            
            HUD.mode = MBProgressHUDModeText;
            HUD.labelText = @"已收藏";
            [sender setBackgroundImage:[UIImage imageNamed:@"favoriteafter"] forState:UIControlStateNormal];
            [HUD showAnimated:YES whileExecutingBlock:^{
                sleep(1);
            } completionBlock:^{
                [HUD removeFromSuperview];
                HUD = nil;
            }];
            
        }else{
            NSLog(@"收藏失败");
        }
        
    }else{
        NSLog(@"取消收藏");
        if ([self addOrDeleteFavorite:del.currentUser.userID houseID:willShowHouse.houseID flag:flag]) {
            HUD = [[MBProgressHUD alloc] initWithView:self.view];
            [self.view addSubview:HUD];
            
            HUD.mode = MBProgressHUDModeText;
            HUD.labelText = @"已取消收藏";
            [sender setBackgroundImage:[UIImage imageNamed:@"favoritebefore"] forState:UIControlStateNormal];
            
            [HUD showAnimated:YES whileExecutingBlock:^{
                sleep(1);
            } completionBlock:^{
                [HUD removeFromSuperview];
                HUD = nil;
                if (self.sourceFrom == 3) {
                    //设置isRefresh，当返回收藏夹界面时刷新
                    del.isRefresh = 4;
                    //返回收藏界面
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }
                
            }];
        }else{
            NSLog(@"取消收藏失败");
        }
        
    }
    
}

#pragma mark 收藏房屋/取消收藏网络操作
-(BOOL)addOrDeleteFavorite:(int)userID houseID:(int)houseID flag:(BOOL)addOrDelete{
    NSString *urlstr;
    if (addOrDelete) {
        urlstr = [NSString stringWithFormat:@"%@favorite/addFavorite?userID=%d&houseID=%d",kHTTPHome,userID,houseID];
    }else{
        urlstr = [NSString stringWithFormat:@"%@favorite/deleteFavorite?userID=%d&houseID=%d",kHTTPHome,userID,houseID];
    }
    
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    
    NSData *data = [request responseData];
    NSDictionary *dic = [jd objectWithData:data];
    int status = [[dic objectForKey:@"status"] intValue];
    if (status) {
        return YES;
    }
    return NO;
}

#pragma mark 联系房东按钮事件
-(void)contactHouseOwner:(id)sender{
    
    //未登录时不能和房东聊天，直接跳到登录界面
    if (!del.isLogin) {
        VOLLoginViewController *loginvc = [self.storyboard instantiateViewControllerWithIdentifier:@"loginController"];
        [self presentViewController:loginvc animated:YES completion:^{
            
        }];
        return;
    }
    
    NSLog(@"联系房东");
    if ([userphone isEqualToString:del.currentUser.userPhone]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您自己就是房东哦！" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];
        [self.view addSubview:alert];
        [alert show];
        
    }
    else{
    VOLChatViewController *ct = [[VOLChatViewController alloc]initWithNibName:@"VOLChatViewController" bundle:nil];
    ct.chatToName =[  NSString stringWithFormat:@"%@%@", userphone,kXMPPLocal] ;
    [self.navigationController pushViewController:ct animated:YES];
    }
}

#pragma mark 去目的地的路径规划
-(void)goDestinationMap
{
    //传值
    VOLGoThereViewController *go = [self.storyboard instantiateViewControllerWithIdentifier:@"VOLGoThereViewController"];
    go.houseID = willShowHouse.houseID;
    [self.navigationController pushViewController:go animated:YES];
}

#pragma mark 描述按钮事件
-(void)goToDesc:(UIButton *)sender{
    VOLDescribeViewController *descVC = [self.storyboard instantiateViewControllerWithIdentifier:@"describeController"];
    if (self.sourceFrom == 0) {//当来自发布房屋时的预览时
        descVC.houseDesc = del.publishHouse.houseDesc;
        descVC.houseNear = del.publishHouse.houseNear;
        descVC.houseTraffic = del.publishHouse.houseTraffic;
    }else{
        descVC.houseDesc = willShowHouse.houseDesc;
        descVC.houseNear = willShowHouse.houseNear;
        descVC.houseTraffic = willShowHouse.houseTraffic;
    }
    [self.navigationController pushViewController:descVC animated:YES];
}

#pragma mark 评论界面
-(void)goToComment:(UIButton *)sender{
    VOLCommentViewController *commentVC = [self.storyboard instantiateViewControllerWithIdentifier:@"allCommentController"];
    commentVC.houseID = willShowHouse.houseID;
    [self.navigationController pushViewController:commentVC animated:YES];
}

#pragma mark 了解房东更多信息
-(void)readMore:(UIButton *)sender{
    NSLog(@"跳转房东详细信息页面");
    if (self.sourceFrom == 0||self.sourceFrom == 1) {
        return;
    }
    PersonDataViewController *personData = [self.storyboard instantiateViewControllerWithIdentifier:@"PersonDataViewController"];
    personData.sourceFrom = 1;
    //传递userID
    personData.userID = houseOwner.userID;
    [self.navigationController pushViewController:personData animated:YES];
}

#pragma mark 添加被允许的便利设施
-(void)allHaveFacility:(Facility *)facility{
    if (facility.shampoo) {
        [facilities addObject:[FacilityIcon facilityIconWithImageName:@"shampoo.png" labelText:@"洗发水"]];
    }
    if (facility.aircondition) {
        [facilities addObject:[FacilityIcon facilityIconWithImageName:@"aircondition.png" labelText:@"空调"]];
    }
    if (facility.kitchen) {
        [facilities addObject:[FacilityIcon facilityIconWithImageName:@"kitchen.png" labelText:@"厨房"]];
    }
    if (facility.wifi) {
        
        [facilities addObject:[FacilityIcon facilityIconWithImageName:@"wifi.png" labelText:@"免费WiFi"]];
    }
    if (facility.hotwater) {
        
        [facilities addObject:[FacilityIcon facilityIconWithImageName:@"hotwater.png" labelText:@"热水"]];
    }
    if (facility.parking) {
        [facilities addObject:[FacilityIcon facilityIconWithImageName:@"parking.png" labelText:@"免费停车"]];
    }
    if (facility.elevator) {
        
        [facilities addObject:[FacilityIcon facilityIconWithImageName:@"elevator.png" labelText:@"电梯"]];
    }
    if (facility.isSmoke) {
        
        [facilities addObject:[FacilityIcon facilityIconWithImageName:@"smoke.png" labelText:@"允许吸烟"]];
    }
    if (facility.isPat) {
        
        [facilities addObject:[FacilityIcon facilityIconWithImageName:@"pat.png" labelText:@"可带宠物"]];
    }
    if (facility.barrierFree) {
        
        [facilities addObject:[FacilityIcon facilityIconWithImageName:@"barrierfree.png" labelText:@"无障碍设施"]];
    }
    if (facility.tv) {
        
        [facilities addObject:[FacilityIcon facilityIconWithImageName:@"tv.png" labelText:@"电视"]];
    }
    if (facility.bathroom) {
        
        [facilities addObject:[FacilityIcon facilityIconWithImageName:@"bathroom.png" labelText:@"淋浴"]];
    }
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 返回方法
-(void)goBack:(id)sender{
    back;
}

#pragma mark 返回房屋类型
-(NSString *)getHouseType:(int)houseType{
    NSString *str;
    switch (houseType) {
        case 0:
            str = @"整套房子";
            break;
        case 1:
            str = @"独立房间";
            break;
        case 2:
            str = @"合租房间";
            break;
            
    }
    return str;
}
#pragma mark - 代理方法
#pragma mark 房屋图片scrollView代理
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.x > 160) {
        UIView *view = [self.view viewWithTag:180];
        view.hidden = YES;
        
    }else{
        UIView *view = [self.view viewWithTag:180];
        view.hidden = NO;
    }
}


#pragma mark alert代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex != 1) return;
    
    __block BOOL isClosed = NO;
    
    
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    
    //设置文字
    HUD.labelText = @"正在关闭...";
    [HUD showAnimated:YES whileExecutingBlock:^{
        
        NSString *urlstr = [NSString stringWithFormat:@"%@house/closeHouseByHouseID?houseID=%d",kHTTPHome,willBeClosedHouseID];
        NSURL *url = [NSURL URLWithString:urlstr];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        [request startSynchronous];
        
        NSData *data = [request responseData];
        NSDictionary *dic = [jd objectWithData:data];
        int status = [[dic objectForKey:@"status"] intValue];
        if (status) {
            NSLog(@"关闭成功");
            //将willBeClosedHouseID置为-1
            willBeClosedHouseID = -1;
            isClosed = YES;
        }
        
        
    } completionBlock:^{
        [HUD removeFromSuperview];
        HUD = nil;
        
        
        HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        
        if (isClosed) {
            //提示关闭成功
            
            
            HUD.labelText = @"关闭成功";
            HUD.mode = MBProgressHUDModeCustomView;
            HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Checkmark.png"]];
            
        }else{
            
            HUD.labelText = @"关闭失败";
            HUD.mode = MBProgressHUDModeText;
        }
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        } completionBlock:^{
            [HUD removeFromSuperview];
            HUD = nil;
            del.isRefresh = 2;
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
    }];
    
    
}

#pragma mark 返回到我的房源界面
-(void)backToRoot{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - 当从其它地方跳转过来时加载相应的信息
#pragma mark 根据userID从服务器加载房东信息
-(void)getHouseOwnerByUserID:(int)userID{
    NSString *urlstr = [NSString stringWithFormat:@"%@user/information?userID=%d",kHTTPHome,userID];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    
    NSData *data = [request responseData];
    if (data != nil) {
        
        NSDictionary *dic = [jd objectWithData:data];
        
        int status = [[dic objectForKey:@"status"] intValue];
        if (status == 0) {
            NSLog(@"房东信息加载失败");
            return;
        }
        
        NSArray *array = [dic objectForKey:@"user"];
        NSDictionary *userInfo = array[0];
        
        houseOwner.userID = [[userInfo objectForKey:@"user_id"] intValue];
        houseOwner.userName = [userInfo objectForKey:@"user_name"];
        houseOwner.userPhone = [userInfo objectForKey:@"user_phone"];
        houseOwner.userHead = [userInfo objectForKey:@"user_head"];
        houseOwner.userRegisterTime = [[userInfo objectForKey:@"user_register_time"] floatValue];
    }
    else{
        NSLog(@"房东信息data为空");
        return;
    }
}
#pragma mark 根据houseID从服务器加载房屋信息
-(void)getHouseByHouseID:(int)houseID{
    
    NSString *urlstr = [NSString stringWithFormat:@"%@house/information?houseID=%d",kHTTPHome,houseID];
    NSURL *url = [[NSURL alloc] initWithString:urlstr];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    [request startSynchronous];
    
    NSData *data = [request responseData];
    if (data != nil) {
        
        NSDictionary *dic = [jd objectWithData:data];
        
        int status = [[dic objectForKey:@"status"] intValue];
        if (status == 0) {
            NSLog(@"房屋信息加载失败");
            return;
        }
        
        NSArray *array = [dic objectForKey:@"house"];
        NSDictionary *houseInfo = array[0];
        
        willShowHouse.houseID = [[houseInfo objectForKey:@"house_id"] intValue];
        willShowHouse.houseType = [[houseInfo objectForKey:@"house_type"] intValue];
        
        willShowHouse.houseProvince = [houseInfo objectForKey:@"house_province"];
        willShowHouse.houseCity = [houseInfo objectForKey:@"house_city"];
        willShowHouse.houseStreet = [houseInfo objectForKey:@"house_street"];
        
        willShowHouse.housePersons = [[houseInfo objectForKey:@"house_persons"] intValue];
        willShowHouse.houseBedroom = [[houseInfo objectForKey:@"house_bedroom"] intValue];
        willShowHouse.houseBed = [[houseInfo objectForKey:@"house_bed"] intValue];
        willShowHouse.houseToilet = [[houseInfo objectForKey:@"house_toilet"] intValue];
        
        willShowHouse.houseTitle = [houseInfo objectForKey:@"house_title"];
        willShowHouse.houseDesc = [houseInfo objectForKey:@"house_desc"];
        
        willShowHouse.housePrice = [[houseInfo objectForKey:@"house_price"] floatValue];
        willShowHouse.houseNear = [houseInfo objectForKey:@"house_near"];
        willShowHouse.houseTraffic = [houseInfo objectForKey:@"house_traffic"];
        
        willShowHouse.houseDate = [[houseInfo objectForKey:@"house_date"] doubleValue];
        willShowHouse.houseExpirationdate = [[houseInfo objectForKey:@"house_expirationdate"] doubleValue];
        
        willShowHouse.houseScore = [[houseInfo objectForKey:@"house_score"] floatValue];
        
        willShowHouse.houseFacility = [[houseInfo objectForKey:@"house_facility"] intValue];
        willShowHouse.houseOwner = [[houseInfo objectForKey:@"house_owner"] intValue];
    }
    else{
        NSLog(@"房屋信息data为空");
        return;
    }
}

#pragma mark 加载房屋图片名字
-(void)getAllHouseImages:(int)houseID{
    NSString *urlstr = [NSString stringWithFormat:@"%@image/searchAllImagesByHouseID?houseID=%d",kHTTPHome,houseID];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    
    NSData *data = [request responseData];
    if (data) {
        NSDictionary *dic = [jd objectWithData:data];
        int status = [[dic objectForKey:@"status"] intValue];
        if (status == 0) {
            NSLog(@"图片加载失败");
            return;
        }
        
        NSArray *array = [dic objectForKey:@"images"];
        for (NSDictionary *obj in array) {
            [houseImageArray addObject:[obj objectForKey:@"image_name"]];
        }
        
    }else{
        NSLog(@"房屋图片data为空");
        return;
    }
}
#pragma mark 下载图片并添加到scrollView中
-(void)loadAllHouseImagesWithHouseID:(int)houseID imageArray:(NSArray *)imageArray imageScrollView:(UIScrollView *)imageScrollView{
    
    //开启新线程下载图片
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for (int i = 0; i < imageArray.count; i++) {
            
            NSString *imageName = imageArray[i];
            //先从本地查找
            //判断图片文件夹是否存在，若不存在则创建
            NSString *imageDocumentPath = [NSString stringWithFormat:@"%@%d/houseImages/%d",kGetDocumentsPath,del.currentUser.userID,houseID];
            if (![manager fileExistsAtPath:imageDocumentPath]) {
                [manager createDirectoryAtPath:imageDocumentPath withIntermediateDirectories:YES attributes:nil error:nil];
            }
            //判断图片是否已经保存在本地，如果有则直接加载，如果没有则去下载
            NSString *imagePath = [NSString stringWithFormat:@"%@%d/houseImages/%d/%@",kGetDocumentsPath,del.currentUser.userID,houseID,imageName];
            
            //如果本地已存在，直接回到主线程去加载
            if ([manager fileExistsAtPath:imagePath]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
                    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(kViewWidth * i, 0, kViewWidth, 200)];
                    imageView.image = image;
                    imageView.contentMode = UIViewContentModeScaleAspectFit;
                    [imageScrollView addSubview:imageView];
                    
                });
                //加载完毕后结束本次循环
                continue;
            }
            
            //如果本地不存在，下载图片
            NSString *urlstr = [NSString stringWithFormat:@"%@%d/%@",kHouseImageHome,houseID,imageName];
            NSURL *url = [NSURL URLWithString:urlstr];
            NSData *data = [NSData dataWithContentsOfURL:url];
            UIImage *image = [UIImage imageWithData:data];
            if (image != nil) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(kViewWidth * i, 0, kViewWidth, 200)];
                    imageView.image = image;
                    imageView.contentMode = UIViewContentModeScaleAspectFit;
                    [imageScrollView addSubview:imageView];
                    //本地保存
                    [data writeToFile:imagePath atomically:YES];
                });
                
            }
        }
        
        
    });
}



#pragma mark 根据便利设施ID加载便利设施信息
-(void)getFacilityByFacilityID:(int)facilityID{
    NSString *urlstr = [NSString stringWithFormat:@"%@facility/information?faclityID=%d",kHTTPHome,facilityID];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request startSynchronous];
    
    NSData *data = [request responseData];
    if (data) {
        NSDictionary *dic = [jd objectWithData:data];
        
        int status = [[dic objectForKey:@"result"] intValue];
        if (status == 0) {
            NSLog(@"便利设施加载失败");
            return;
        }
        
        NSArray *array = [dic objectForKey:@"facility"];
        NSDictionary *facilityInfo = array[0];
        
        houseFacility.shampoo = [[facilityInfo objectForKey:@"f_shampoo"] intValue];
        houseFacility.aircondition = [[facilityInfo objectForKey:@"f_aircondition"] intValue];
        houseFacility.kitchen = [[facilityInfo objectForKey:@"f_kitchen"] intValue];
        houseFacility.wifi = [[facilityInfo objectForKey:@"f_wifi"] intValue];
        houseFacility.hotwater = [[facilityInfo objectForKey:@"f_hotwater"] intValue];
        houseFacility.parking = [[facilityInfo objectForKey:@"f_parking"] intValue];
        houseFacility.elevator = [[facilityInfo objectForKey:@"f_elevator"] intValue];
        houseFacility.isSmoke = [[facilityInfo objectForKey:@"f_issmoke"] intValue];
        houseFacility.isPat = [[facilityInfo objectForKey:@"f_ispat"] intValue];
        houseFacility.barrierFree = [[facilityInfo objectForKey:@"f_barrier_free"] intValue];
        houseFacility.tv = [[facilityInfo objectForKey:@"f_tv"] intValue];
        houseFacility.bathroom = [[facilityInfo objectForKey:@"f_bathroom"] intValue];
    }else{
        NSLog(@"便利设施data为空");
        return;
    }
    
}


@end





